package com.smile.config;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.smile.config.RequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 01
 * @program wrapper-demo
 * @description 签名拦截器
 * @create 2018-12-24 21:08
 * @since 1.0
 **/
@Slf4j
public class SignatureInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("[preHandle] executing... request uri is {}", request.getRequestURI());
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        System.out.println("进入到SignatureInterceptor中");
        System.out.println(request.getRequestURI());
        // 修改拦截路径，包含两个可能的登录接口路径
        if ("/api/auth/sso/doLogin".equals(request.getRequestURI()) || "/shopping/auth/doLogin".equals(request.getRequestURI())) {
            if (isJson(request)) {
                // 获取json字符串
                String jsonParam = new RequestWrapper(request).getBodyString();
                log.info("[preHandle] json数据 : {}", jsonParam);
                JSONObject entries = JSONUtil.parseObj(jsonParam);
                // 从请求体中获取用户名和密码，兼容两种不同的字段名
                String userName = entries.containsKey("username") ? entries.get("username").toString() : entries.get("name").toString();
                String password = entries.containsKey("password") ? entries.get("password").toString() : entries.get("pwd").toString();
                UserUtilsByLogin.setName(userName);
                UserUtilsByLogin.setPwd(password);
                // 如果没有loginType参数，设置一个默认值
                UserUtilsByLogin.setLoginType(entries.containsKey("loginType") ? entries.get("loginType").toString() : "system");
                // 验签逻辑...略...
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 判断本次请求的数据类型是否为json
     *
     * @param request request
     * @return boolean
     */
    private boolean isJson(HttpServletRequest request) {
        if (request.getContentType() != null) {
            return request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) ||
                    request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE);
        }

        return false;
    }
}

